import 'package:get/get.dart';
import '../model/user_model.dart';
import '../data/user_data.dart';
import 'like_state.dart';
import 'follow_state.dart';

/// 用户状态管理
/// 使用GetX进行全局状态管理
class UserState extends GetxController {
  /// 当前登录用户
  final Rx<UserModel?> _currentUser = Rx<UserModel?>(null);

  /// 所有用户列表
  final RxList<UserModel> _allUsers = <UserModel>[].obs;

  /// 是否已初始化
  final RxBool _isInitialized = false.obs;

  /// 获取当前用户
  UserModel? get currentUser => _currentUser.value;

  /// 获取所有用户
  List<UserModel> get allUsers => _allUsers;

  /// 是否已初始化
  bool get isInitialized => _isInitialized.value;

  /// 是否已登录
  bool get isLoggedIn => _currentUser.value != null;

  @override
  void onInit() {
    super.onInit();
    _initializeUsers();
  }

  /// 初始化用户数据
  void _initializeUsers() {
    _allUsers.value = UserData.getDefaultUsers();
    _isInitialized.value = true;
  }

  /// 用户登录
  bool login(String username, String password) {
    // 先从注册用户中查找
    UserModel? user = _allUsers.firstWhereOrNull((u) => u.username == username);
    // 如果没找到，再从默认用户中查找
    user ??= UserData.getUserByUsername(username);

    if (user != null && user.password == password) {
      _currentUser.value = user;

      // 登录成功后，设置相关状态管理的用户ID
      _updateRelatedStates(user.id);

      return true;
    }
    return false;
  }

  /// 更新相关状态管理的用户ID
  void _updateRelatedStates(String userId) {
    try {
      // 设置点赞状态的用户ID
      final likeState = Get.find<LikeState>();
      likeState.setCurrentUserId(userId);

      // 设置关注状态的用户ID
      final followState = Get.find<FollowState>();
      followState.setCurrentUserId(userId);
    } catch (e) {
      // 如果状态管理类还未初始化，忽略错误
      print('Related states not initialized yet: $e');
    }
  }

  /// 用户注册
  void register(String username, String password) {
    final user = UserModel(
      id: '${_allUsers.length + 1}',
      username: username,
      password: password,
      nickname: username,
      avatar: 'assets/images/avatar1.png',
      signature: '',
    );
    _allUsers.add(user);

    // 注册成功后自动登录并设置相关状态
    _currentUser.value = user;
    _updateRelatedStates(user.id);
  }

  /// 用户登出
  void logout() {
    _currentUser.value = null;

    // 登出时清空相关状态
    _clearRelatedStates();
  }

  /// 清空相关状态管理的用户ID
  void _clearRelatedStates() {
    try {
      // 清空点赞状态的用户ID
      final likeState = Get.find<LikeState>();
      likeState.setCurrentUserId('');

      // 清空关注状态的用户ID
      final followState = Get.find<FollowState>();
      followState.setCurrentUserId('');
    } catch (e) {
      // 如果状态管理类还未初始化，忽略错误
      print('Related states not initialized yet: $e');
    }
  }

  /// 更新当前用户信息
  void updateCurrentUser(UserModel updatedUser) {
    if (_currentUser.value != null) {
      _currentUser.value = updatedUser;
      // 同时更新用户列表中的信息
      final index = _allUsers.indexWhere((user) => user.id == updatedUser.id);
      if (index != -1) {
        _allUsers[index] = updatedUser;
      }
    }
  }

  /// 根据ID获取用户
  UserModel? getUserById(String id) {
    return UserData.getUserById(id);
  }

  /// 根据用户名获取用户
  UserModel? getUserByUsername(String username) {
    // 先从注册用户中查找
    UserModel? user = _allUsers.firstWhereOrNull((u) => u.username == username);
    // 如果没找到，再从默认用户中查找
    return user ?? UserData.getUserByUsername(username);
  }

  /// 根据昵称获取用户
  UserModel? getUserByNickname(String nickname) {
    return UserData.getUserByNickname(nickname);
  }

  /// 搜索用户
  List<UserModel> searchUsers(String query) {
    if (query.isEmpty) return _allUsers;

    return _allUsers.where((user) {
      return user.nickname.toLowerCase().contains(query.toLowerCase()) ||
          user.username.toLowerCase().contains(query.toLowerCase()) ||
          user.signature.toLowerCase().contains(query.toLowerCase());
    }).toList();
  }

  /// 更新用户头像
  void updateUserAvatar(String avatarPath) {
    if (_currentUser.value != null) {
      final updatedUser = _currentUser.value!.copyWith(avatar: avatarPath);
      updateCurrentUser(updatedUser);
    }
  }

  /// 更新用户签名
  void updateUserSignature(String signature) {
    if (_currentUser.value != null) {
      final updatedUser = _currentUser.value!.copyWith(signature: signature);
      updateCurrentUser(updatedUser);
    }
  }

  /// 更新用户昵称
  void updateUserNickname(String nickname) {
    if (_currentUser.value != null) {
      final updatedUser = _currentUser.value!.copyWith(nickname: nickname);
      updateCurrentUser(updatedUser);
    }
  }
}
